package com.kotlin.android.api

import com.kotlin.android.api.api.*
import com.kotlin.android.api.config.Env
import com.kotlin.android.ktx.ext.e


/**
 *
 * Created on 2020/5/13.
 *
 * @author o.s
 */
class ApiRepository private constructor() {

    /**
     * Api缓存池
     * key：Api类型
     * value：Api对象
     */
    private val repo = HashMap<Class<*>, Any>()

    companion object {
        val instance by lazy { ApiRepository() }
    }

    fun <T : Any> getApi(service: Class<T>): T {
        val api = repo[service]
        return if (api != null) {
            api as? T ?: generateApi(service)
        } else {
            generateApi(service)
        }
    }

    private fun <T : Any> generateApi(service: Class<T>): T {
        val api = RetrofitRepository.instance.getRetrofit(ApiType.obtain(service).baseUrl).create(service)
        repo[service] = api
        return api
    }

    enum class ApiType(val service: Class<*>, var baseUrl: String) {
        MISC(ApiMisc::class.java, Env.instance.hostMisc),
        CINEMA(ApiCinema::class.java, Env.instance.hostCinema),
        USER(ApiUser::class.java, Env.instance.hostUser),
        TICKET(ApiTicket::class.java, Env.instance.hostTicket),
        PAYMENT(ApiPayment::class.java, Env.instance.hostPayment),
        CARD(ApiCard::class.java, Env.instance.hostCard),
        SNACK(ApiSnack::class.java, Env.instance.hostSnack),
        COUPON(ApiCoupon::class.java, Env.instance.hostCoupon),
        ACTIVITY(ApiActivity::class.java, Env.instance.hostActivity),
        MKT(ApiMkt::class.java, Env.instance.hostMkt),
        COUNT(ApiCount::class.java, Env.instance.hostCount);

        companion object {
            fun obtain(service: Class<*>): ApiType {
                return when (service) {
                    MISC.service -> MISC
                    CINEMA.service -> CINEMA
                    USER.service -> USER
                    TICKET.service -> TICKET
                    PAYMENT.service -> PAYMENT
                    CARD.service -> CARD
                    SNACK.service -> SNACK
                    COUPON.service -> COUPON
                    ACTIVITY.service -> ACTIVITY
                    MKT.service -> MKT
                    COUNT.service -> COUNT
                    else -> MISC
                }
            }
        }
    }
}